package com.qfmy.web.app.service.impl.novel;

import com.qfmy.common.Thread.ThreadPoolConfig;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.Novel;
import com.qfmy.model.entity.novel.NovelComment;
import com.qfmy.model.vo.novel.NovelCommentVo;
import com.qfmy.web.app.mapper.novel.NovelCommentMapper;
import com.qfmy.web.app.mapper.novel.NovelMapper;
import com.qfmy.web.app.service.agent.ChatService;
import com.qfmy.web.app.service.novel.NovelCommentService;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.qfmy.web.app.service.impl.novel
 * @date 2025/9/12
 * @description 小说评论表
 */
@Slf4j
@Service
public class NovelCommentServiceImpl implements NovelCommentService {

    /**
     * 注入mapper
     */
    @Autowired
    private NovelCommentMapper novelCommentMapper;

    /**
     * 注入小时mapper
     */
    @Autowired
    private NovelMapper novelMapper;

    /**
     * 注入chatService
     */
    @Autowired
    private ChatService chatService;


    /**
     * 根据小说id获取评论列表
     * @param novelId
     * @return
     */
    @Override
    public List<NovelCommentVo> getCommentsByNovelId(Integer novelId) {
        // 1.获取用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        Long userId = loginUser.getUserId();
        //2.获取评论列表
        List<NovelComment> novelComments = novelCommentMapper.getCommentsByNovelId(novelId,userId);
        //转换
        return convertVo(novelComments);
    }

    /**
     * 添加评论
     * @param novelComment
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addComment(@NotNull NovelComment novelComment) {
        // 获取当前用户并校验登录状态
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        if (loginUser == null) {
            throw new BaseException(ResultCodeEnum. ILLEGAL_REQUEST);
        }
        // 获取用户ID
        Long userId = loginUser.getUserId();
        //智能检测评论是否包含敏感信息
        chatService.checkByAi(novelComment.getContent());
        // 设置用户ID
        novelComment.setUserId(userId);
        // 添加评论并校验结果
        int rows = novelCommentMapper.addComment(novelComment);
        if (rows <= 0) {
            log.error("评论添加失败，novelComment:{}", novelComment);
            throw new BaseException(404,"评论发布失败，请重试");
        }
        // 提取变量，提升可读性
        Integer novelId = novelComment.getNovelId();
        BigDecimal rating = novelComment.getRating().multiply(BigDecimal.valueOf(2));

        // 异步更新小说评分
        CompletableFuture.runAsync(() -> {
            try {
                // 查询小说信息并校验
                Novel novel = novelMapper.selectById(novelId);
                if (novel == null) {
                    log.error("更新评分失败，小说不存在，novelId:{}", novelId);
                    return;
                }

                // 获取当前评分和评分人数
                BigDecimal currentScore = novel.getScore();
                Long scoreCount = novel.getScoreCount();
                scoreCount = scoreCount == null ? 0 : scoreCount; // 处理null值

                // 计算新评分（处理首次评分场景）
                BigDecimal newScore;
                if (scoreCount <= 0) {
                    newScore = rating.setScale(2, RoundingMode.HALF_UP);
                } else {
                    currentScore = currentScore == null ? BigDecimal.ZERO : currentScore;
                    newScore = currentScore.multiply(new BigDecimal(scoreCount))
                            .add(rating)
                            .divide(new BigDecimal(scoreCount + 1), 2, RoundingMode.HALF_UP);
                }
                // 更新评分
                novelMapper.updateScore(novelId, newScore, scoreCount + 1);
                log.info("小说评分更新成功，novelId:{}, newScore:{}, newCount:{}",
                        novelId, newScore, scoreCount + 1);

            } catch (Exception e) {
                log.error("异步更新小说评分失败，novelId:{}, error:", novelId, e);
            }
        }, ThreadPoolConfig.executorService);
    }

    /**
     * 判断用户是否已经评论
     * @param novelId
     * @return
     */
    @Override
    public Boolean isComment(Integer novelId) {
        //获取用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断用户是否登录
        if (loginUser == null) {
            return false;
        }
        Long userId = loginUser.getUserId();
        //根据用户id和小说id查询评论
        Integer count  = novelCommentMapper.selectCommentById(novelId, userId);
        //判断是否已经评论
        return count > 0;
    }


    /**
     * 转换
     * @param novelComments
     * @return
     */
    @NotNull
    private List<NovelCommentVo> convertVo(List<NovelComment> novelComments) {
        //判断集合是否为空
        if (novelComments == null || novelComments.isEmpty()) {
            return Collections.emptyList();
        }
        List<NovelCommentVo> novelCommentVos = novelComments.stream().map(novelComment -> new NovelCommentVo(
                novelComment.getCommentId(),
                novelComment.getUserId(),
                novelComment.getUsername(),
                novelComment.getAvatar(),
                novelComment.getRating(),
                novelComment.getContent(),
                novelComment.getCommentTime(),
                novelComment.getLikeCount(),
                novelComment.getReplyCount(),
                novelComment.getIsLiked()
        )).collect(Collectors.toList());
        return novelCommentVos;
    }
}
